#include "loginwindow.h"
#include "registerwindow.h"
#include "playerwindow.h"
#include <QSettings>
LoginWindow::LoginWindow(QObject *parent):QObject(parent)
{
    engine.load(QUrl("qrc:/qml_login.qml"));

    //配置信号与槽 qt4
    rootObject = engine.rootObjects().first();

    connect(rootObject,SIGNAL(btnclicked(QString,QString,int)),
            this,SLOT(slot_btnclicked(QString,QString,int)));
}
                    //0表示登录 1表示注册
void LoginWindow::slot_btnclicked(QString userName, QString passWord, int flag)
{
    qDebug()<<userName<<passWord<<flag;
    if(flag)
    {
        RegisterWindow* pr = new RegisterWindow;
        connect(pr,&RegisterWindow::sendRegisterInfo,this,&LoginWindow::slot_recvUserInfo);
    }
    else
    {
        engine_suc.load(QUrl(QStringLiteral("qrc:/qml_message.qml")));
        // 获取根对象（ApplicationWindow）
        rootObject_msg = engine_suc.rootObjects().first();
        // 通过 objectName 查找 Text 控件
        QObject* textTip = rootObject_msg->findChild<QObject*>("tip");
        bool ok = DbManager::getDbPtr()->userLogin(userName,passWord);
        if(ok)
        {
            //登录成功

            //1.如果登录成功，条抓页面，显示 播放器 页面
            PlayerWindow* p = new PlayerWindow(userName);
            p->show();

            //2.登录成功，将登陆用户的信息 保存到ini配置文件中
            QSettings* set = new QSettings("user.ini",QSettings::IniFormat);
            //添加两个键值对
            set->setValue("/user/username",userName);
            set->setValue("/user/password",passWord);

            //3.关闭当前

            rootObject->setProperty("visible", false);

        }
        else
        {
            //登录失败
            if (textTip) {
                // 修改 Text 的属性
                textTip->setProperty("text", "登录失败！账号或密码错误");

            }
        }

    }
}

void LoginWindow::slot_recvUserInfo(QString name, QString pass)
{
    //找到 qml文件中 两个输入框
    QObject* username = rootObject->findChild<QObject*>("username");
    QObject* password = rootObject->findChild<QObject*>("password");
   // qDebug()<<username<<password;
    qDebug()<<name<<pass;
    //更改属性 text
    if(username && password)
    {
        username->setProperty("text",name);
        password->setProperty("text",pass);qDebug()<<name<<pass;
    }
}
